# -*- coding: utf-8 -*-
import time
from resource_management import *
from resource_management.core.resources.system import Execute
from resource_management.libraries.functions.check_process_status import check_process_status
from resource_management.libraries.script.script import Script

from dolphin_env import dolphin_env
import commands

class DolphinApiService(Script):
    def install(self, env):
        import params
        env.set_params(params)
        Execute('rm -rf /usr/hdp/current/dolphinscheduler')
        Execute('wget {0} -O dolphinscheduler.tar.gz'.format(params.download_url))
        Execute('tar -zxvf dolphinscheduler.tar.gz -C {0} && rm -rf dolphinscheduler.tar.gz'.format(params.hdp_base_dir))
        Execute('rm -rf {1} && mv {0}/apache-dolphinscheduler* {1}'.format(params.hdp_base_dir, params.dolphin_home))
        Execute('wget -P {0}/lib/ {1}'.format(params.dolphin_home, params.jdbc_driver_download_url))
        Execute('ln -s {0} /usr/hdp/current/dolphinscheduler'.format(params.dolphin_home))

    def configure(self, env):
        import params
        params.pika_slave = True
        env.set_params(params)

        dolphin_env()

    def start(self, env):
        import params
        env.set_params(params)
        self.configure(env)

        # init
        init_cmd = format("sh " + params.dolphin_home + "/script/create-dolphinscheduler.sh")
        Execute(init_cmd, user=params.dolphin_user)

        # upgrade
        upgrade_cmd = format("sh " + params.dolphin_home + "/script/upgrade-dolphinscheduler.sh")
        Execute(upgrade_cmd, user=params.dolphin_user)
        no_op_test = format("ls {dolphin_pidfile_dir}/api-server.pid >/dev/null 2>&1 && ps `cat {dolphin_pidfile_dir}/api-server.pid` | grep `cat {dolphin_pidfile_dir}/api-server.pid` >/dev/null 2>&1")

        start_cmd = format("sh " + params.dolphin_bin_dir + "/dolphinscheduler-daemon.sh start api-server")
        Execute(start_cmd, user=params.dolphin_user, not_if=no_op_test)

    def stop(self, env):
        import params
        env.set_params(params)
        stop_cmd = format("sh " + params.dolphin_bin_dir + "/dolphinscheduler-daemon.sh stop api-server")
        Execute(stop_cmd, user=params.dolphin_user)
        time.sleep(5)

    def status(self, env):
        import status_params
        env.set_params(status_params)
        check_process_status(status_params.dolphin_run_dir + "api-server.pid")

if __name__ == "__main__":
    DolphinApiService().execute()